package com.tiza.xiaoyoubao.ui.fragment;

import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tianze.library.utils.AppUtils;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.entity.EditInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;

import org.simple.eventbus.EventBus;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by mapple on 17/3/6.
 * 修改用户名第二步
 */

public class ChangeUserNameSecFragment extends BaseFragment {

    @BindView(R.id.et_userName)
    EditText et_userName;
    @BindView(R.id.et_verCode)
    EditText et_verCode;
    @BindView(R.id.et_passWord)
    EditText et_passWord;

    @BindView(R.id.buttonVerify)
    Button buttonVerify;

    //输入的短信验证码
    private String userVerify;
    //获取的短信验证码
    private String verifyCode = "";

    private String userName, passWord,etCode;
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    private static final int SECONDS = 60;

    private int nowSeconds = SECONDS;

    private static Handler sHandler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (nowSeconds >= 2) {
                nowSeconds--;
                buttonVerify.setText(nowSeconds + "s后重发");
                sHandler.postDelayed(this, 1000);
            } else {
                nowSeconds = SECONDS;
                buttonVerify.setText("获取验证码");
                buttonVerify.setEnabled(true);
            }
        }
    };
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_user_name_sec;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }
    @OnClick({R.id.buttonVerify,R.id.bt_commit})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.buttonVerify:
                doVerify();
                break;
            case R.id.bt_commit:
                String message = check();
                if (TextUtils.isEmpty(message)) {
                    changeUserPhone();
                } else {
                    showWarnDialog(message);
                    return;
                }
                break;
            default:
                break;
        }
    }

    private String check() {
        userName = et_userName.getText().toString().trim();
        if (!AppUtils.isMobile(userName))
            return "请输入正确的手机号";
        etCode=et_verCode.getText().toString().trim();
        if (!etCode.equals(verifyCode)||etCode.length()==0)
            return "请输入正确的短信验证码";
        passWord = et_passWord.getText().toString().trim();
        String passWord1 = Hawk.get(Constants.KEY_USER_PASSWD, "");
        if (passWord.length() == 0||!passWord.equals(passWord1))
            return "请输入正确的登录密码";
        return "";
    }
    private void doVerify() {
        buttonVerify.setEnabled(false);
        sHandler.post(runnable);
        ApiHttpClient.verify(ChangeUserNameSecFragment.this, userInfo.getWebzzCmsBuyerInfo().getTelphone(),
                             new JsonCallback<String>(String.class, true) {

                                 @Override
                                 public void onBefore(Request request) {
                                     super.onBefore(request);
                                 }

                                 @Override
                                 public void onError(Call call, Exception e) {
                                     toast("验证码获取失败");
                                     sHandler.removeCallbacks(runnable);
                                     nowSeconds = SECONDS;
                                     buttonVerify.setText("获取验证码");
                                     buttonVerify.setEnabled(true);
                                 }

                                 @Override
                                 public void onResponse(ResponseInfo<String> response) {
                                     int code = response.getCode();
                                     String message = response.getMessage();
                                     if (code == 1) {
                                         showWarnDialog(message);
                                         sHandler.removeCallbacks(runnable);
                                         nowSeconds = SECONDS;
                                         buttonVerify.setText("获取验证码");
                                         buttonVerify.setEnabled(true);
                                         return;
                                     }
                                     Map<String, Object> _map = response.getFirstEntity();
                                     verifyCode = String.valueOf(_map.get("verify"));
                                 }

                                 @Override
                                 public void onAfter() {
                                     super.onAfter();
                                 }
                             });
    }


    private void changeUserPhone() {
        buttonVerify.setEnabled(false);
        sHandler.post(runnable);
        ApiHttpClient.setUserInfo(ChangeUserNameSecFragment.this, userName, passWord,"5",
                                  new JsonCallback<String>(String.class, true) {

                                      @Override
                                      public void onBefore(Request request) {
                                          super.onBefore(request);
                                      }

                                      @Override
                                      public void onError(Call call, Exception e) {
                                          showWaitingDialog();
                                      }

                                      @Override
                                      public void onResponse(ResponseInfo<String> response) {
                                          int code = response.getCode();
                                          String message = response.getMessage();
                                          if (code == 1) {
                                              showWarnDialog(message);
                                              return;
                                          }
                                          sHandler.removeCallbacks(runnable);
                                          toast("手机号修改成功!");
                                          EventBus.getDefault().post(new EditInfo(EditInfo
                                                                                          .TYPE_USER_PHONE, userName),
                                                                     Constants.TAG_SET_USER_PHONE_SUCCESS
                                          );
                                          finish();
                                      }

                                      @Override
                                      public void onAfter() {
                                          super.onAfter();
                                      }
                                  }
        );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sHandler.removeCallbacks(runnable);
    }
}
